package com.ccc.ka.util;

import cn.hutool.core.date.DateUtil;
import com.ccc.ka.entity.Key;
import com.ccc.ka.mapper.KeyMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Date;

@Component
public class KASequence {

    @Autowired
    private KeyMapper keyMapper;

    public String getSeq(String prefix, int digit) throws KAException {
        return getSeqWithMiddleDate(prefix, "", null, digit);
    };

    public String getSeqWithMiddle(String prefix, String middle, int digit) throws KAException {
        return getSeqWithMiddleDate(prefix, middle, null, digit);
    };

    public String getSeqWithMiddleDate(String prefix, String middle, Date date, int digit) throws KAException {
        Assert.notNull(prefix, "前缀为空");
        middle = StringUtils.isNotBlank(middle) ? middle : "";
        String dateStr = null != date ? DateUtil.format(date, "yyyyMMdd") : null;
        String kName = prefix + middle + dateStr;
        Key key = new Key();
        key.setKName(kName);
        //根据kName查询kIndex
        Integer kIndex = 0;
        synchronized (this){
            kIndex = keyMapper.selectByName(kName);
            //kIndex为空则添加key数据
            if(null == kIndex){
                key.setKIndex(0);
                keyMapper.insert(key);
                kIndex = 0;
            }
            keyMapper.updateByName(key);
        }
        return kName + getDigitStr(digit, kIndex + 1);
    };

    public static String getDigitStr(int digit, int number) throws KAException {
        if(digit > 11 || Math.pow(10, digit) < number){
            throw new KAException("位数：" + digit + "，数字：" + number + "异常！");
        }
        return String.format("%0"+digit+"d", number);
    }

}
